<?php if (!defined("BASEPATH")) exit("No direct script access allowed"); ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winUser; // edit ablak
		var userForm; // form panel

		var store = new Ext.data.JsonStore({
			totalProperty: 'total',
			root: 'results',
			sortInfo: {field: 'usrEmail', direction: 'ASC'},
			remoteSort: true,
			proxy : new Ext.data.HttpProxy({
				url: '<?=site_url()?>admin/get_user/<?=$type?>',
				method: 'GET'
			}),
			fields: [
				{name: 'usrId'},
				{name: 'usrEmail'},
				{name: 'usrPassword'},
				{name: 'usrNewsletter'},
				{name: 'usrLogged'},
				{name: 'usrRegistered'},
				{name: 'usrLastupd'},
				{name: 'usrVerify'},
				{name: 'grpName'},
				{name: 'couList'},
				{name: 'cityList'},
				{name: 'insList'},
				{name: 'pageCatList'},
				{name: 'couNameList'},
				{name: 'cityNameList'},
				{name: 'insNameList'},
				{name: 'pageCatNameList'},
				{name: 'u2gInsId'},
				{name: 'u2gInsName'},
				{name: 'u2gInsNameRaw'},
				{name: 'u2gInsAddressRaw'},
				{name: 'u2gInsWebRaw'},
				{name: 'u2gCityId'},
				{name: 'u2gPostalCode'}
			]
		});
		
		/* innerGrid
		function usr2ent(i) {
			Ext.Ajax.request({url: '<?=site_url()?>admin/getUsr2ent', params: 'usrId=' + $('div[id^="innerGrid"]')[i].getAttribute('id').replace('innerGrid', ''), success: function() {
					i++;
					if($('div[id^="innerGrid"]').length >= i+1) {
						usr2ent(i);
					}
				}
			});
		}
		*/
		
		store.on('load', function() {
			/*for(var i = 1; i <= gridCnt; i++) {
				console.info(i);
				innerGrid.render('innerGrid' + i);
			}*/
			var innerGrids = $('div[id^="innerGrid"]');
			if(innerGrids.length > 0) {
				usr2ent(0);
			}
		})

		<? if($type == "Admin") { ?>
		var contextMenuUser = new Ext.menu.Menu({
			items: [{
				id: 'u2eDelete',
				iconCls: 'application_form_delete',
				text: ''
			}],
			listeners: {
				itemclick: function(item) {
					switch (item.id) {
						case 'u2eDelete': {
							Ext.Ajax.request({url: '<?=site_url()?>admin/usr2grp_insert_update', params: 'usrId=' + Ext.getCmp('userGrid').getSelectionModel().getSelections()[0].data.usrId, success: function() {
								store.reload(store.lastOptions);
								}
							});
						} break;
					}
				}
			}
		});
		<? } ?>
		
		var grid = new Ext.grid.GridPanel({
			store: store,
			id: 'userGrid',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>',
				listeners: {
				}
			},
			columns: [
				{id: 'usrEmail', header: '<?=$this->db->escape_str($this->lang->line("E-MAIL_ADDRESS"))?>', width: 130, sortable: true, dataIndex: 'usrEmail', renderer: function(value, cell, record) {
					return value;
				}},

				<? /*{header: '<?=$this->db->escape_str($this->lang->line("NEWSLETTER"))?>', width: 80, sortable: true, valign: 'top', dataIndex: 'usrNewsletter', renderer: function(val) {return '<span style="color:' + ((val == 'I')?('green'):('red')) + ';">' + ((val == 'I')?('<?=$this->db->escape_str($this->lang->line("YES"))?>'):('<?=$this->db->escape_str($this->lang->line("NO"))?>')) + '</span>';}}, */ ?>
				{header: '<?=$this->db->escape_str($this->lang->line("TIME_OF_REGISTRATION"))?>', width: 150, sortable: true, dataIndex: 'usrRegistered'},
				{header: '<?=$this->db->escape_str($this->lang->line("TIME_OF_LAST_LOGIN"))?>', width: 150, sortable: true, dataIndex: 'usrLastupd'},
				{header: '<?=$this->db->escape_str($this->lang->line("CONFORMED"))?>', width: 100, sortable: true, dataIndex: 'usrVerify', renderer: function(val) {return '<span style="color:' + ((!val)?('green'):('red')) + ';">' + ((!val)?('<?=$this->db->escape_str($this->lang->line("YES"))?>'):('<?=$this->lang->line("NO")?>')) + '</span>';}},
				<? if($type == "Admin") { ?>
				{header: '<?=$this->db->escape_str($this->lang->line("SUPERADMIN_ADMIN"))?>', width: 150, sortable: true, dataIndex: 'grpName', renderer: function(val, index, record) { var SuperAdmin = false; var Admin = false; for(var i in val) {if
					(i == 1) SuperAdmin = true; if(i == 2) Admin = true;}; return '<span ' + ((SuperAdmin || Admin)?('style="color:green"'):('')) + '>' + val[i] + ((record.data.u2gInsName)?('<br/>' + record.data.u2gInsName):('')) + '</span>';}},
				<? } ?>
				//{id: 'InnerGrid', header: '', width: 400, sortable: false, dataIndex: 'usrRegistered', renderer: function(val, index, record) { return '<div id="innerGrid' + record.data.usrId + '"></div>'; }}
				{id: 'InnerGrid', header: '<?=$this->db->escape_str($this->lang->line("PRIVILEGES"))?>', width: 100, sortable: false, dataIndex: 'grpName', renderer: function(val, index, record) { 
					var SuperAdmin = false; var Admin = false; 
					for(var i in val) {if(i == 1) SuperAdmin = true; if(i == 2) Admin = true;};
					if(SuperAdmin) return '';
					if(Admin) return '<a onclick=\"return false;\"><?=$this->db->escape_str($this->lang->line("PRIVILEGES"))?></a>'; 
				}}
			],
			stripeRows: true,
			autoExpandColumn: 'usrEmail',
			autoHeight: true,
			autoWidth: true,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),

			listeners: {
					viewready: function(view) {

					}, 
			<? if($type == "Admin") { ?>
				rowcontextmenu: function(grid, rowIndex, event) {
					event.stopEvent();
					//console.info(Ext.getCmp('userGrid').getSelectionModel().getSelections()[0].data);
					if(Ext.getCmp('userGrid').getSelectionModel().getSelections().length > 0) {
						if(Ext.getCmp('userGrid').getSelectionModel().getSelections()[0].data.u2gInsName || Ext.getCmp('userGrid').getSelectionModel().getSelections()[0].data.u2gInsId) {
							Ext.getCmp('u2eDelete').setText('<?=$this->db->escape_str($this->lang->line("RESET_OF_POSSIBLE_CONNECTION"))?> - ' + Ext.getCmp('userGrid').getSelectionModel().getSelections()[0].data.u2gInsName.split(' (<?=$this->lang->line("ADDRESS")?>:')[0] );
							contextMenuUser.showAt(event.xy);
						}
					}
				},
				<? } ?>

				cellclick: function(grid, rowIndex, columnIndex, event) {
					if(columnIndex == 4) {
						var record = grid.getStore().getAt(rowIndex);
						if(record.data.u2gInsId || record.data.u2gInsName) {
							if(record.data.u2gInsId) {
								Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_CONNECT_TO_USER_THE_INSTITUTE_BELOW"))?>: <b>' + record.data.u2gInsName + '</b>?' , function(btn) {
									if(btn == 'yes') {
										Ext.Ajax.request({url: '<?=site_url()?>admin/usr2grp_insert_update', params: 'usrId=' + record.data.usrId + '&insId=' + record.data.u2gInsId, success: function() {
											store.reload(store.lastOptions);
											}
										});
									}
								});
							} else {

								Ext.Msg.show({
									msg: '<?=$this->db->escape_str($this->lang->line("THE_INSTITUTE_YOU_WOULD_LIKE_TO_CONNECT_TO_USER_IS_NOT_EXIST"))?>: <b>' + record.data.u2gInsName + '</b>!<br/><?=$this->db->escape_str($this->lang->line("YOU_WANT_TO_RECORD"))?>',
									buttons: Ext.Msg.YESNO,
									fn: function(btn) {
										if(btn == 'yes') {
											Ext.Ajax.request({
												url: '<?=site_url()?>admin/getCategoryVal',
												params: { entity: 'INS', id: -1, insName: record.data.u2gInsNameRaw, insAddress: record.data.u2gInsAddressRaw, insWeb: record.data.u2gInsWebRaw, insPostalCode: record.data.u2gPostalCode, insCityId: record.data.u2gCityId},
												scripts: true
											});
										}
									},
									icon: Ext.MessageBox.INFO
								});

							}
						}

					} else if(columnIndex == 5) {
						var record = grid.getStore().getAt(rowIndex);
						
						var Admin = false; 
						for(var i in record.data.grpName) {if(i == 2) Admin = true;};
						if(!Admin) return false;
						
						winUserPrivileges = new Ext.Window({
							iconCls: 'application_form_edit',
							layout:'',
							bodyStyle: 'background-color:white',
							autoScroll: true,
							modal: true,
							width:700,
							floating: true,
							minWidth: 700,
							height:400,
							minHeight: 400,
							closeAction:'close',
							maximizable: false,
							title: '<?=$this->db->escape_str($this->lang->line("PRIVILEGES"))?> - ' + record.data.usrEmail,

							listeners: {
								close: function() {
									store.reload(store.lastOptions);
								}
							},

							items:[
								new Ext.FormPanel({
									padding: 0,
									labelAlign: 'right',
									labelWidth: 50,
									id: 'frmUserPrivileges',
									autoHeight: true,
									autoWidth: true,
									border: false,
									defaultType: 'textfield',
									waitMsgTarget: true,
									items: [
										
									]

								})
							]

						});
						winUserPrivileges.show(this);
						Ext.Ajax.request({url: '<?=site_url()?>admin/getUsr2ent', params: 'usrId=' + record.data.usrId
						});
					}
				},

				rowdblclick: function(grid, rowIndex, event) {

					if(parseInt(rowIndex) >= 0) {
						var record = grid.getStore().getAt(rowIndex);
					} else {
						var record = new Object();
						record.data = new Object();
						record.data.usrId = 1;
					}
					Ext.Ajax.request({
						url: '<?=site_url()?>admin/getCategoryVal',
						params: { entity: 'USER', id: ((parseInt(rowIndex) >= 0)?(''):((rowIndex == 'new')?('-'):('--'))) + record.data.usrId},
						scripts: true
					});

				}
			},
			border: false,

			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_USER"))?>',
						handler: function(){
							grid.fireEvent('rowdblclick', grid, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("CANCEL_USER"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_USER"))?> (' + grid.getSelectionModel().getSelections()[0].data.usrEmail + ')?' , removeUser);
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/email_go.png',
						text: '<?=$this->db->escape_str($this->lang->line("SENDING_E-MAIL"))?>',
						ref: '../sendBtn',
						disabled: true,
						handler: function(){

							var record = grid.getSelectionModel().getSelected();

							if(winUser) {
								winUser.close();
							}
							winUser = new Ext.Window({
								iconCls: 'application_go',
								layout:'',
								bodyStyle: 'background-color:white',
								autoScroll: true,
								modal: true,
								width:500,
								floating: true,
								minWidth: 500,
								height:430,
								minHeight: 430,
								closeAction:'close',
								maximizable: false,
								title: '<?=$this->db->escape_str($this->lang->line("SENDING_E-MAIL"))?> - ' + record.data.usrEmail,

								listeners: {
									close: function() {
										store.reload(store.lastOptions);
									}
								},

								items:[{

											border: false,

											items: [
												letterForm = new Ext.FormPanel({
													padding: 10,
													labelAlign: 'right',
													labelWidth: 50,
													autoHeight: true,
													autoWidth: true,
													border: false,
													defaultType: 'textfield',
													waitMsgTarget: true,
													items: [{
															hidden: true,
															inputType: 'hidden',
															name: 'email',
															value: record.data.usrEmail
														}, {
															xtype:'fieldset',
															title: '<?=$this->db->escape_str($this->lang->line("SUBJECT"))?>',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '<?=$this->db->escape_str($this->lang->line("SUBJECT"))?>',
																name: 'subject',
																maxLength: 255,
																maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
																allowBlank: false,
																blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
																anchor:'100%'
															}]
														},{
															xtype:'fieldset',
															title: '<?=$this->db->escape_str($this->lang->line("TEXT"))?>',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '<?=$this->db->escape_str($this->lang->line("TEXT"))?>',
																xtype: 'htmleditor',
																enableColors: true,
																enableLinks: true,
																enableFont: true,
																enableSourceEdit: true,
																allowBlank: false,
																blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
																name: 'text',
																anchor:'100%',
																height: 200,
																listeners: {
																	render: function(editor) {
																		editor.getToolbar().insertButton(editor.getToolbar().items.length, {
																			iconCls: 'upload-icon',
																			handler: function(b,e) {
																				Ext.Msg.prompt('Insert Image', 'Image URL', function(btn, txt) {
																					if (btn == 'ok') {
																						editor.relayCmd('insertimage', txt);
																					}
																				});                                            
																			}
																		});
																	}
																}
															}]
														}
													]

												})
											]

										}

									],

									bbar: {
										items: [{
											text: '<?=$this->db->escape_str($this->lang->line("SENDING"))?>',
											handler: send,
											icon: '<?=MEDIA?>icon/email_go.png'
										}, {
											xtype: 'tbseparator'
										},{
											text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
											handler: function() {
												winUser.close();
											},
											icon: '<?=MEDIA?>icon/cancel.png'
										}, {
											xtype: 'tbseparator'
										},{
											text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
											handler: function() {
												letterForm.getForm().reset();
											}
										}],
										buttonAlign : 'right'
									}

							});
							winUser.show(this);

						}
					}
					<? if(Common::isSuperAdmin()) { ?>
					, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_SUPERADMIN"))?>',
						handler: function() {
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WANT_TO_REGISTER_YET_ANOTHER_ONE_SUPERADMIN"))?>' , function(btn) {
								if(btn == 'yes') {
									grid.fireEvent('rowdblclick', grid, 'new-superadmin', new Object());
								}
							});
						}
					}
					<? } ?>
				]
			},

			bbar: 
				new Ext.PagingToolbar({
					pageSize: <?=$this->config->item("adminGridPageSize")?>,
					store: store,
					displayInfo: true,
					plugins: new Ext.ux.ProgressBarPager()
				}),
			
			plugins:[
				new Ext.ux.grid.Search({
					minChars:2,
					iconCls: 'icon-zoom',
					searchText:'<?=$this->db->escape_str($this->lang->line("SEARCH"))?>',
					position:'top',
					minCharsTipText:'<?=$this->db->escape_str($this->lang->line("MINIMUM_TWO_CHARACTERS_IS_REQUIRED"))?>',
					selectAllText: '<?=$this->db->escape_str($this->lang->line("SELECT_ALL"))?>',
					width:200,
					disableIndexes:[],
					autoFocus:true
				})]

		});

		grid.render('grid-table-user-<?=$type?>');
		
		grid.getSelectionModel().on('selectionchange', function(sm){
			grid.removeBtn.setDisabled(sm.getCount() < 1);
			grid.sendBtn.setDisabled(sm.getCount() < 1);
		});

		store.load({params:{start:0, limit:<?=$this->config->item("adminGridPageSize")?>}});

		function removeUser(btn) {
			if(btn == 'yes') {
				Ext.Ajax.request({url: '<?=site_url()?>admin/data_edit_insert_update', params: 'del=1&ENTITY=USER&usrId=' + grid.getSelectionModel().getSelections()[0].data.usrId, success: function() {
					store.reload(store.lastOptions);
					}
				});
			}
		}

		function send() {
			if(letterForm.getForm().isDirty()) {
				letterForm.getForm().submit({
					url: '<?=site_url()?>admin/email_send',
					success: function(form, resp){
						if(resp.result.error) {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
								msg: resp.result.error,
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.ERROR
							});
						} else if(resp.result.message) {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("THE_FOLLOWING_EVENT_HAPPENED"))?>',
								msg: resp.result.message,
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.INFO,
							});
							winUser.close();
						} else {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("MESSAGE_SENT"))?>',
								msg: '<?=$this->db->escape_str($this->lang->line("MESSAGE_IS_SUCCESSFULLY_SENT_TO_THE_USER"))?>',
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.INFO
							});
							winUser.close();
						}
					}
				});
			} else {
				winUser.close();
			}
		}

	})
</script>


<div id="grid-table-user-<?=$type?>"></div>